import type { Router, LocationQueryRaw } from 'vue-router';
import NProgress from 'nprogress'; // progress bar

import { useUserStore } from '@/store';
import { isLogin } from '@/utils/auth';
import { slashToDot } from '@/utils/index';

export default function setupUserLoginInfoGuard(router: Router) {
  router.beforeEach(async (to, from, next) => {
    NProgress.start();
    const userStore = useUserStore();
    if (isLogin()) {
      if (userStore.role) {
        next();
      } else {
        try {
          await userStore.info();
          next();
        } catch (error) {
          // 刷新页面重新获取用户信息时报错401需要退出登录回到login页面
          if (to.name === 'login' || to.name === 'activeUser') {
            next();
          } else {
            await userStore.logout(false);
            if (from.name === 'login') {
              next({ name: 'login' });
            } else {
              next({
                name: 'login',
                query: {
                  redirect: slashToDot(to.fullPath),
                  ...to.query,
                } as LocationQueryRaw,
              });
            }
          }
        }
      }
    } else if (to.name === 'login' || to.name === 'activeUser') {
      next();
    } else {
      next({
        name: 'login',
        query: {
          redirect: slashToDot(to.fullPath),
          ...to.query,
        } as LocationQueryRaw,
      });
    }
  });
}
